package com.servlet.demo;

import com.servlet.demo.core.UserCoreService;
import com.servlet.demo.dto.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    // 初始化用户信息服务
    private UserCoreService userCoreService = new UserCoreService();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        // 获取账号密码
        String account = request.getParameter("account");
        String password = request.getParameter("password");
        // 账号基本信息验证
        if ("".equals(account) || "".equals(password)) {
            request.setAttribute("message", "账号密码不能为空");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }
        User user = userCoreService.getUserByLogin(account, password);
        if (user == null) {
            request.setAttribute("message", "账号或密码错误");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }
        // 保存登陆信息到session
        HttpSession session = request.getSession();
        // 登陆用户信息保存到KEY为sd_user的session下面
        session.setAttribute("sd_user", user);
        // 设定session过期时间；session过期时间单位s，没有活动10s后过期
        session.setMaxInactiveInterval(10);

        // 即将跳转到loginInfo页面，设定信息
        request.setAttribute("user", user);
        request.getRequestDispatcher("/loginInfo.jsp").forward(request, response);
    }
}
